<template>
  <div>
    <el-input
        v-model="searchQuery"
        placeholder="搜索课程名称、课程ID或课程代码"
        suffix-icon="el-icon-search"
        @input="handleSearch"
        style="width: 300px; margin-bottom: 20px;"
    />
    <el-button type="primary" @click="openAddCourseDialog">新增课程</el-button>
    <el-button type="success" @click="exportCourses">导出课程</el-button>

    <el-table :data="filteredCourses.slice((currentPage - 1) * pageSize, currentPage * pageSize)" stripe style="width: 100%">
      <el-table-column prop="course_id" label="课程ID" width="80"></el-table-column>
      <el-table-column prop="course_code" label="课程代码"></el-table-column>
      <el-table-column prop="course_name" label="课程名称"></el-table-column>
      <el-table-column prop="course_description" label="课程描述"></el-table-column>
      <el-table-column label="审批状态">
        <template slot-scope="scope">
          <el-button
              :type="scope.row.course_approval_status === 'pass' ? 'success' : scope.row.course_approval_status === 'rejected' ? 'danger' : 'warning'"
              size="small"
              disabled
          >
            {{ scope.row.course_approval_status === 'pass' ? '已批准' : scope.row.course_approval_status === 'rejected' ? '已拒绝' : '待审批' }}
          </el-button>
          <el-button
              v-if="scope.row.course_approval_status === 'rejected'"
              size="small"
              type="info"
              @click="viewRejectionReason(scope.row)"
              style="margin-left: 10px;"
          >
            查看原因
          </el-button>
          <el-button
              v-if="scope.row.course_approval_status === 'pending'"
              size="small"
              type="danger"
              @click="cancelOperation(scope.row)"
              style="margin-left: 10px;"
          >
            撤回操作
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200">
        <template slot-scope="scope">
          <el-button size="mini" type="primary" @click="openEditCourseDialog(scope.row)">修改</el-button>
          <el-button size="mini" type="danger" @click="deleteCourse(scope.row.course_id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-size="pageSize"
        :total="filteredCourses.length"
        layout="total, prev, pager, next, jumper"
        style="margin-top: 20px;"
    />

    <el-dialog :title="'拒绝原因'" :visible.sync="rejectionDialogVisible">
      <p>{{ rejectionReason }}</p>
      <div slot="footer" class="dialog-footer">
        <el-button @click="rejectionDialogVisible = false">关闭</el-button>
      </div>
    </el-dialog>
    <!-- 新增或编辑课程对话框 -->
    <el-dialog :title="isEditing ? '修改课程' : '新增课程'" :visible.sync="dialogVisible">
      <el-form :model="currentCourse" label-width="120px">
        <el-form-item label="课程代码">
          <el-input v-model="currentCourse.course_code"></el-input>
        </el-form-item>
        <el-form-item label="课程名称">
          <el-input v-model="currentCourse.course_name"></el-input>
        </el-form-item>
        <el-form-item label="课程描述">
          <el-input type="textarea" v-model="currentCourse.course_description"></el-input>
        </el-form-item>
        <el-form-item label="课程图片">
          <vue-img-cutter
          ref="imgCutter"
          width="240"
          height="180"
          :cutWidth="420"
          :cutHeight="250"
          :outputSize="5000"
          :sizeChange="false"
          outputType="png"
          :accept="imgType"
          :drag="true"
          @cutDown="cutDown"
          ></vue-img-cutter>
          <img v-if="imgUrl" :src="imgUrl" alt="课程图片" class="preview-img">
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveCourse">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import VueImgCutter from 'vue-img-cutter';
import { fetchCourses } from '@/api/teacherGetCourses'
import {teacherAddCourse} from "@/api/teacherAddCourse";
import axios from '@/utils/request';

export default {
  components: { VueImgCutter },
  data() {
    return {
      imgType:"image/gif, image/jpeg ,image/png, image/jpg",
      searchQuery: "",
      currentPage: 1,
      pageSize: 10,
      dialogVisible: false,
      isEditing: false,
      currentCourse: {
        course_id: null,
        course_code: "",
        course_name: "",
        course_description: "",
        course_img: "", // 课程图片字段
      },
      courses: [],
      tempNewCourse: null,
      rejectionDialogVisible: false,  // 控制拒绝原因对话框的显示
      rejectionReason: '',  // 存储拒绝的原因
      imgUrl: '',
      imgFile:null,
    };
  },
  computed: {
    filteredCourses() {
      const query = this.searchQuery.toLowerCase(); // 转为小写
      return this.courses.filter(course =>
          String(course.course_id).toLowerCase().includes(query) || // 课程ID
          course.course_code.toLowerCase().includes(query) || // 课程代码
          course.course_name.toLowerCase().includes(query) // 课程名称
      );
    },
  },
  methods: {
    handleSearch() {
      this.currentPage = 1;
    },
    openAddCourseDialog() {
      this.isEditing = false;
      this.dialogVisible = true;
    },
    openEditCourseDialog(course) {
      this.isEditing = true; // 表示是编辑模式
      this.currentCourse = { ...course }; // 将课程信息复制到 currentCourse
      this.dialogVisible = true; // 显示对话框
    },
    async getCourses() {
      const teacherId = localStorage.getItem('teacherId');
      if (!teacherId) {
        this.$message.error('教师ID未找到');
        return;
      }
      try {
        // 调用封装的 API 请求方法
        const courses = await fetchCourses(teacherId);
        this.courses = courses;
      } catch (error) {
        this.$message.error(error.message);
      }
    },
    async uploadImage() {
      if (!this.imgFile) {
        this.$message.error("请先裁剪并选择图片");
        throw new Error("图片未选择或裁剪");
      }
      const formData = new FormData();
      formData.append('courseImg', this.imgFile); // 上传图片文件
      // formData.append('fileName', this.imgFile.fileName); // 上传图片的文件名（如果后端需要）
      try {
        const response = await axios.post('/upload/courseImage', formData, {
          headers: { 'Content-Type': 'multipart/form-data' },
        });
        console.log(response);
        // 上传成功后的处理逻辑（例如保存图片路径）
      } catch (error) {
        console.error('图片上传失败:', error);
        if (error.response) {
          // 打印错误的详细信息
          console.error('错误响应:', error.response.data);
          console.error('错误状态:', error.response.status);
        }
        this.$message.error('图片上传失败，请重试');
        throw error; // 上传失败后抛出错误，终止后续流程
      }
    },
    // 新增或修改课程
    async saveCourse() {
      if (!this.currentCourse.course_code || !this.currentCourse.course_name || !this.currentCourse.course_description) {
        this.$message.error('请填写完整的课程信息');
        return;
      }
      await this.uploadImage(); // 上传图片
      // this.currentCourse.course_img = filePath; // 使用后端返回的路径
      const updatedCourseData = {
        course_code: this.currentCourse.course_code,
        course_name: this.currentCourse.course_name,
        course_description: this.currentCourse.course_description,
        course_img: this.currentCourse.course_img,
        teacher_id: localStorage.getItem('teacherId'), // 从本地存储获取教师ID
      };
      try {
        if (this.isEditing) {
          // 编辑课程接口
          const response = await axios.put(`/teacher/updateCourse/${this.currentCourse.course_id}`, updatedCourseData);
          // this.$message.success(response.data.message);
          console.log(response.data);
          this.$message({
            message:'课程修改成功',
            type: 'warning',
            offset: '80'
          });
        } else {
          // 新增课程接口
          const response = await teacherAddCourse(updatedCourseData);
          const newCourse = response.data;
          this.courses.push(newCourse);
          // console.log(response);
          // this.$message.success('课程新增成功，等待管理员审核');
          this.$message({
            message:'课程新增成功，等待管理员审核',
            type: 'warning',
            offset: '80'
          });
        }
        await this.getCourses(); // 刷新课程列表
        this.dialogVisible = false; // 关闭对话框
      } catch (error) {
        console.error('操作失败:', error);
        this.$message.error('操作失败，请重试');
      }finally {
        // 清空当前课程数据
        this.currentCourse = {
          course_code: '',
          course_name: '',
          course_description: '',
          course_img: '', // 清空图片路径
          course_id: null,
        };
        // 如果需要重置图片上传的内容，也可以在这里清空相关变量
        this.imgFile = null; // 假设 imgFile 用于存储图片文件
        this.imgUrl = null;
      }
    },
    // 删除课程
    async deleteCourse(courseId) {
      try {
        const response = await axios.delete(`/teacher/deleteCourse/${courseId}`);
        // this.$message.success(response.data.message);
        console.log(response.data);
        this.$message({
          message:'课程删除成功',
          type: 'success',
          offset: '80'
        });
        await this.getCourses(); // 刷新课程列表
      } catch (error) {
        console.error('删除课程失败:', error);
        this.$message.error('删除课程失败，请重试');
      }
    },
    cancelOperation(course) {
      const index = this.courses.findIndex(c => c.course_id === course.course_id);
      if (index !== -1) {
        // 撤回操作时删除新增的课程
        if (this.tempNewCourse && this.tempNewCourse.course_id === course.course_id) {
          this.courses.splice(index, 1); // 删除本次新增的课程
          this.tempNewCourse = null; // 清空临时数据
        } else {
          // 撤回操作时将审批状态恢复为“已批准”
          this.courses[index].course_approval_status = "pass";
        }
      }
    },
    exportCourses() {
      // 实现导出功能
      this.$message.success("导出功能待实现");
    },
    handleCurrentChange(newPage) {
      this.currentPage = newPage;
    },
    cutDown(imgData) {
      this.imgUrl = imgData.dataURL;
      this.imgFile = imgData.file;
      // console.log(this.imgFile)
      this.currentCourse.course_img = imgData.fileName; // 保存裁剪后的图片名
      this.$forceUpdate();
      console.log(imgData)
    },
    viewRejectionReason(course) {
      // 将拒绝原因显示在对话框中
      this.rejectionReason = course.rejection_reason || '暂无拒绝原因';  // 如果没有拒绝原因则提示默认信息
      this.rejectionDialogVisible = true;  // 打开对话框
    },
  },
  created() {
    // 组件创建时自动调用 getCourses 方法
    this.getCourses();
  },
};
</script>

<style scoped>
.dialog-footer {
  text-align: right;
}
.container {
   padding: 50px 30px;
 }
.container .learn-course {
  float: left;
  position: relative;
  width: 240px;
  height: 300px;
  font-size: 12px;
  box-sizing: border-box;
  vertical-align: top;
  color: #131B26;
  overflow: visible;
  cursor: pointer;
  margin-right: 40px;
  margin-bottom: 0;
}
.course-cover .el-image{
  border-radius: 8px;
}
.preview-img {
  width: 300px;
  height: auto;
  margin-top: 10px;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
</style>
